package softtech.app.secretcaller;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

import com.mobpartner.android.publisher.http.MobPartnerAdCampaign;
import com.mobpartner.android.publisher.http.MobPartnerAdObject;
import com.mobpartner.android.publisher.views.MobPartnerAdBanner;
import com.mobpartner.android.publisher.views.MobPartnerAdInterstitial;
import com.mobpartner.android.publisher.views.MobPartnerAdListener;
import com.mobpartner.android.publisher.views.MobPartnerAdView;
import com.mobpartner.android.publisher.views.MobPartnerMobwall;

import android.R.color;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Vibrator;
import android.provider.CallLog;
import android.telephony.TelephonyManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.TranslateAnimation;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;

public class ActivityContactList extends Activity {
	
	final String Pool_ID = "54118";

	MobPartnerAdInterstitial interstitial;
	
	final String TAG = "ACTIVITY CONTACT LIST";
	
	final static int FLAG_CALLING = 1;
	
	final int FLAG_NOT_CALL = 0;
	
	static int mFlagCalling;
	
	static String mPhoneNumberCalling;

	DatabaseHandler db;

	public static int USER_ID ;

	ViewAlertDialogManager dialogAlert;

	private static final int PICKFILE_RESULT_CODE = 1;

	static int mode;
	
	static int mode_history;

	Context context;

	ViewFlipper vflipMain;
	Animation slide_in_left, slide_out_right;

	MenuItem mniActionNewContact, mniActionSendSMS,
			mniActionSaveContact , mniActionMoveToTrash;

	ViewAlertDialogManager mAlertDialog;
	
	/**
	 * Sliding panel
	 */
	AdapterSlidingMenu adapterSliding;
	ListView lvSlidingMenu;
	private LinearLayout linearSlidingPanel;
	private boolean isExpanded;
	private DisplayMetrics metrics;
	private RelativeLayout menuPanel;
	private int panelWidth;

	FrameLayout.LayoutParams menuPanelParameters;
	FrameLayout.LayoutParams slidingPanelParameters;
	LinearLayout.LayoutParams headerPanelParameters;
	LinearLayout.LayoutParams listViewParameters;

	Button btnLogout;

	/**
	 * List Contact Form
	 */
	// List View
	ListView lvContactSecret;

	// Edittext
	EditText edtContactSecretFilter;

	// Adapter
	AdapterSecretContacts adapterSecretContacts;

	// ArrayList
	ArrayList<DatabaseContact> listContact, listContactSecretFilter;

	/**
	 * Contact Information Form
	 */
	// ImageView
	ImageView imgAvatarContact;

	// Button
	Button btnCallContact, btnSendMessage , btnDelete , btnEdit;

	// TextView
	TextView tvContactName, tvPhoneNumber, tvLatestCall, tvLatestsms,
			tvSyncStatus;
	
	// Linear Show History
	LinearLayout linearShowSMS, linearShowCall;
	
	// Current data
	DatabaseContact mContact;

	/**
	 * Send SMS Form
	 */

	// Edittext
	EditText edtContentSMS, edtPhoneToSendSms;
	
	// Button
	Button btnSendSmsPageSendSms, btnClearContentSms;
	
	// ListView show contact
	ListView lvShowContactSendSms;	

	// TextView
	TextView tvNumberCharacter;

	/**
	 * Edit & Create New Contact
	 */
	// Edittext
	EditText edtEditContactName, edtEditPhoneNumber, edtAvatarPath;

	// Button
	Button btnChooseAvatar;
	
	// Image
	ImageView imgChangeAvatarEdit;
	
	// Flag to check is create new
	Boolean isCreateNew;

	/**
	 * Settings
	 */
	// LinearLayout
	LinearLayout linearShowChangePassword, linearChangePassword,
			linearShowChangeSecurityKey, linearChangeSecurityKey
			, linearRateApp , linearOtherApp ,linearShareApp , linearSignOut
			, linearAboutUs , linearFakeApp ;
	ScrollView linearParentSettings;
	View viewShowSetting;
	EditText edtSettingOldPassword, edtSettingPassword, edtSettingRePassword,
			edtSettingSecurityKey, edtSettingReSecurityKey;

	Button btnPasswordSave ,btnSecurityKeySave ;
	
	/**
	 * Linear List call & sms
	 */
	ListView lvListCall;
	ArrayList<DatabaseContact> listLastEvent;
	
	/**
	 * Linear Sms Chat
	 */
	ArrayList<DatabaseSMS> listChatSms;
	AdapterChatSms adapterSms;
	ListView lvListChat;
	EditText edtSmsContentSubmit;
	Button btnSmsSubmit;
	ImageView imgChooseImageForMMS;
	
	/**
	 * Linear Tab host
	 */
	LinearLayout linearTabhost;
	LinearLayout imgHistorySmsShow,imgHistoryCallShow,
		imgContactsShow ,imgSettingShow , imgKeypadShow;
	
	/**
	 * Linear Call log
	 */
	ListView lvListCallLog;
	
	/**
	 * Linear keypad
	 */
	ArrayList<ImageButton> listSecurityImageButton;
	String phoneNumberKeypadPage;
	TextView tvPhoneNumberFromKeypad;
	ImageView imgDeletePhoneNumberFromKeypad;
	LinearLayout linearNumberKeypadResult;
	ImageButton ibtnCallKeypad , ibtnSaveContactKeypad;
	
	/**
	 * Linear Call profile
	 */
	Button btnCreateContactFromDetail, btnUpdateContactFromDetail;
	ImageView imgStatusCallDetail, imgCallFromDetail ;
	LinearLayout linearSendSmsFromDetail , linearCallFromDetail;
	TextView tvTimeCallDetail , tvDateCallDetail;
	DatabaseCall mCallProfile;
	
	/**
	 * Linear Fake app
	 */
	EditText edtAppFakeName;
	ImageView imgCheckNameFake;
	GridView grdListIconFake;
	AdapterFakeIcon adapterFakeIcon;
	
	/**
	 * Linear Choose contact to update
	 */
	ListView lvContactSecretUpdate;
	EditText edtContactSecretFilterUpdate;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_contact_list);
		context = this;
		mode = 0;
		setID();
		init();
		setFunctionForControls();
		startService();
	}

	public void startService(){
		registerReceiver(broadcastUpdateForm, new IntentFilter(ConstantsFileName.TAG_BROADCAST));
		
		interstitial = new MobPartnerAdInterstitial(context, Pool_ID);
		interstitial.setMobPartnerAdListener(mInsterstitialListener);
    	interstitial.fetchAds();	
	}
	
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			switch (mode) {
			case 0:
//				openMenuSliding();
				break;
			case 1:
				selectPage(0);
				break;
			case 2:
				selectPage(0);
				break;
			case 3:
				selectPage(0);
				break;
			case 4:
				if(viewShowSetting.getVisibility()==View.GONE){
					showHideLinearSettingContent(0);
				}
				break;
			case 5:
				break;
			case 6:
				initListCallForm(2);
				selectPage(5);
				break;
			case 7:
				break;
			case 8:
				break;
			case 9:
				initListCallForm(1);
				selectPage(8);
				break;
			case 10:
				selectPage(4);
				break;
			case 11:
				selectPage(9);
				break;
			default:
				selectPage(0);
				break;
			}
			return true;
		case R.id.action_new_contact:
			mContact = null;
			isCreateNew = true;
			selectPage(3);
			break;
//		case R.id.action_edit_contact:
//			isCreateNew = false;
//			selectPage(3);
//			break;
		case R.id.action_send_sms:
			selectPage(2);
//			if(isSendSMSSuccess()){
//				selectPage(1);
//			}else{
//				dialogAlert = new ViewAlertDialogManager();
//				dialogAlert.showAlertDialog(context, "Can't send sms",
//						"The content sms is error or your device can't not send sms.", false);
//			}
				
			break;
		case R.id.action_save_contact:
			if(mode==3){
				if (saveContactToContactList()) {
					initListContact();
					initContactProfile();
					selectPage(1);
				} else {
					dialogAlert = new ViewAlertDialogManager();
					dialogAlert.showAlertDialog(context, "Input error",
							"Please fill input correctly. ", false);
				}
			}else if(mode ==10){
				String newName = edtAppFakeName.getText().toString();
				if(newName.trim().length() > 0 && adapterFakeIcon.getSelectedPosition() != -1){
					ToolsSaveFile tsf = new ToolsSaveFile();
					String old_name = tsf.LoadContentFile(context, ConstantsFileName.FILE_NAME_OLD_SHORTCUT);
					if(old_name.trim().length()>0){
						ControlPhoneAction.deleteShortCut(context, old_name);
					}
					
					ControlPhoneAction.addShortcut(context, newName, adapterFakeIcon.getItem(adapterFakeIcon.getSelectedPosition()));
					
					tsf.SaveContentFile(context, ConstantsFileName.FILE_NAME_OLD_SHORTCUT, newName.trim() );
					
				}else {
					mAlertDialog = new ViewAlertDialogManager();
					mAlertDialog.showAlertDialog(context, "Information error!",
							"Please enter new app's name and new icon !",
							false);
				}
				
			}
			

			break;
		
		case R.id.action_log_out:
			ToolsSaveFile tsf = new ToolsSaveFile();
			tsf.SaveContentFile(context, ConstantsFileName.FILE_ID_LOG_IN, "");
			Intent intent = new Intent(ActivityContactList.this,
					ActivityLogin.class);
			startActivity(intent);
			finish();
			break;
		case R.id.action_move_to_trash:
			if(!(mCallProfile== null || mCallProfile.equals(null))){
				db.deleteCaller(mCallProfile);
				initListCallForm(1);
				selectPage(8);
			}
			break;
//		case R.id.action_show_menu:
//			ControlsSyncSecretContact taskSyContact = new ControlsSyncSecretContact(context);
//			taskSyContact.execute(null,null,null);
//			openMenuSliding();
//			break;
		}
		return true;
	}

	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.menu_contact_list, menu);

		mniActionNewContact = (MenuItem) menu.findItem(R.id.action_new_contact);
//		mniActionEditContact = (MenuItem) menu
//				.findItem(R.id.action_edit_contact);

		mniActionSendSMS = (MenuItem) menu.findItem(R.id.action_send_sms);
		mniActionSaveContact = (MenuItem) menu
				.findItem(R.id.action_save_contact);

		mniActionMoveToTrash = (MenuItem) menu.findItem(R.id.action_move_to_trash);

		// init visible
		mniActionNewContact.setVisible(true);
		mniActionSendSMS.setVisible(false);
		mniActionSaveContact.setVisible(false);
		mniActionMoveToTrash.setVisible(false);
		return true;
	}

	/**
	 * Set ID
	 */
	void setID() {

		vflipMain = (ViewFlipper) findViewById(R.id.vflipMain);

		// Set ID for contact list form
		edtContactSecretFilter = (EditText) findViewById(R.id.edtContactSecretFilter);
		lvContactSecret = (ListView) findViewById(R.id.lvContactSecret);

		// Set ID for contact profile form
		imgAvatarContact = (ImageView) findViewById(R.id.imgAvatarContact);

		btnCallContact = (Button) findViewById(R.id.btnCallContact);
		btnSendMessage = (Button) findViewById(R.id.btnSendMessage);

		btnDelete = (Button) findViewById(R.id.btnDelete);
		btnEdit = (Button) findViewById(R.id.btnEdit);
		
		tvContactName = (TextView) findViewById(R.id.tvContactName);
		tvPhoneNumber = (TextView) findViewById(R.id.tvPhoneNumber);
		tvLatestCall = (TextView) findViewById(R.id.tvLatestCall);
		tvLatestsms = (TextView) findViewById(R.id.tvLatestsms);
		tvSyncStatus = (TextView) findViewById(R.id.tvSyncStatus);
		
		linearShowCall = (LinearLayout) findViewById(R.id.linearShowCall);
		linearShowSMS = (LinearLayout) findViewById(R.id.linearShowSMS);

		// Set ID for send SMS form
		tvNumberCharacter = (TextView) findViewById(R.id.tvNumberCharacter);
		edtContentSMS = (EditText) findViewById(R.id.edtContentSMS);
		edtPhoneToSendSms = (EditText) findViewById(R.id.edtPhoneToSendSms);
		lvShowContactSendSms = (ListView) findViewById(R.id.lvShowContactSendSms);
		btnSendSmsPageSendSms = (Button) findViewById(R.id.btnSendSmsPageSendSms);
		btnClearContentSms = (Button) findViewById(R.id.btnClearContentSms);

		// set ID for edit and create new contact form
		edtEditContactName = (EditText) findViewById(R.id.edtEditContactName);
		edtEditPhoneNumber = (EditText) findViewById(R.id.edtEditPhoneNumber);
		edtAvatarPath = (EditText) findViewById(R.id.edtAvatarPath);
		btnChooseAvatar = (Button) findViewById(R.id.btnChooseAvatar);
		imgChangeAvatarEdit = (ImageView) findViewById(R.id.imgChangeAvatarEdit);

		// set ID for setting
		linearShowChangePassword = (LinearLayout) findViewById(R.id.linearShowChangePassword);
		linearChangePassword = (LinearLayout) findViewById(R.id.linearChangePassword);
		linearShowChangeSecurityKey = (LinearLayout) findViewById(R.id.linearShowChangeSecurityKey);
		linearChangeSecurityKey = (LinearLayout) findViewById(R.id.linearChangeSecurityKey);
		linearRateApp = (LinearLayout) findViewById(R.id.linearRateApp);
		linearSignOut = (LinearLayout) findViewById(R.id.linearSignOut);
		linearOtherApp = (LinearLayout) findViewById(R.id.linearOtherApp);
		linearShareApp = (LinearLayout) findViewById(R.id.linearShareApp);
		linearAboutUs = (LinearLayout) findViewById(R.id.linearAboutUs);
		linearParentSettings = (ScrollView) findViewById(R.id.linearParentSettings);
		linearFakeApp = (LinearLayout) findViewById(R.id.linearFakeApp);
		
		edtSettingOldPassword =  (EditText) findViewById(R.id.edtSettingOldPassword);
		edtSettingPassword = (EditText) findViewById(R.id.edtSettingPassword);
		edtSettingRePassword = (EditText) findViewById(R.id.edtSettingRePassword);
		edtSettingSecurityKey = (EditText) findViewById(R.id.edtSettingSecurityKey);
		edtSettingReSecurityKey  = (EditText) findViewById(R.id.edtSettingReSecurityKey);
		
		btnPasswordSave  = (Button) findViewById(R.id.btnPasswordSave);
		btnSecurityKeySave = (Button) findViewById(R.id.btnSecurityKeySave);
		
		viewShowSetting = (View) findViewById(R.id.viewShowSetting);
		
		// set ID for List Call
		lvListCall = (ListView) findViewById(R.id.lvListCall);
		
		// set Id for sliding panel
		metrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(metrics);
		panelWidth = (int) ((metrics.widthPixels)*0.75);
		
		menuPanel = (RelativeLayout) findViewById(R.id.menuPanel);
		menuPanelParameters = (FrameLayout.LayoutParams) menuPanel.getLayoutParams();
		menuPanelParameters.width = panelWidth;
		menuPanel.setLayoutParams(menuPanelParameters);
		
		linearSlidingPanel = (LinearLayout) findViewById(R.id.linearSlidingPanel);
		slidingPanelParameters = (FrameLayout.LayoutParams) linearSlidingPanel.getLayoutParams();
		slidingPanelParameters.width = metrics.widthPixels;
		linearSlidingPanel.setLayoutParams(slidingPanelParameters);
		
		lvSlidingMenu = (ListView) findViewById(R.id.lvSlidingMenu);
		
		btnLogout = (Button) findViewById(R.id.btnLogout);
		
		// Set Id for chat form
		lvListChat = (ListView) findViewById(R.id.lvListChat);
		edtSmsContentSubmit = (EditText) findViewById(R.id.edtSmsContentSubmit);
		btnSmsSubmit = (Button) findViewById(R.id.btnSmsSubmit);
		imgChooseImageForMMS = (ImageView) findViewById(R.id.imgChooseImageForMMS);
		
		// Set Id for Linear tab host
		imgHistorySmsShow = (LinearLayout) findViewById(R.id.imgHistorySmsShow);
		imgHistoryCallShow = (LinearLayout) findViewById(R.id.imgHistoryCallShow);
		imgContactsShow = (LinearLayout) findViewById(R.id.imgContactsShow);
		imgSettingShow = (LinearLayout) findViewById(R.id.imgSettingShow);
		imgKeypadShow = (LinearLayout) findViewById(R.id.imgKeypadShow);
		linearTabhost = (LinearLayout) findViewById(R.id.linearTabhost);
		
		// Set Id for Linear Call log
		lvListCallLog = (ListView) findViewById(R.id.lvListCallLog);
		
		// Set Id for page keypad
		listSecurityImageButton = new ArrayList<ImageButton>();
		listSecurityImageButton
				.add((ImageButton) findViewById(R.id.ibtnSecurityNumber0));
		listSecurityImageButton
				.add((ImageButton) findViewById(R.id.ibtnSecurityNumber1));
		listSecurityImageButton
				.add((ImageButton) findViewById(R.id.ibtnSecurityNumber2));
		listSecurityImageButton
				.add((ImageButton) findViewById(R.id.ibtnSecurityNumber3));
		listSecurityImageButton
				.add((ImageButton) findViewById(R.id.ibtnSecurityNumber4));
		listSecurityImageButton
				.add((ImageButton) findViewById(R.id.ibtnSecurityNumber5));
		listSecurityImageButton
				.add((ImageButton) findViewById(R.id.ibtnSecurityNumber6));
		listSecurityImageButton
				.add((ImageButton) findViewById(R.id.ibtnSecurityNumber7));
		listSecurityImageButton
				.add((ImageButton) findViewById(R.id.ibtnSecurityNumber8));
		listSecurityImageButton
				.add((ImageButton) findViewById(R.id.ibtnSecurityNumber9));
		listSecurityImageButton.add((ImageButton) findViewById(R.id.ibtnSecurityNumberStar));
		listSecurityImageButton.add((ImageButton) findViewById(R.id.ibtnSecurityNumberSharp));
		
		imgDeletePhoneNumberFromKeypad = (ImageView) findViewById(R.id.imgDeletePhoneNumberFromKeypad);
		tvPhoneNumberFromKeypad = (TextView) findViewById(R.id.tvPhoneNumberFromKeypad);
		linearNumberKeypadResult = (LinearLayout) findViewById(R.id.linearNumberKeypadResult);
		ibtnCallKeypad	= (ImageButton) findViewById(R.id.ibtnCallKeypad);
		ibtnSaveContactKeypad = (ImageButton) findViewById(R.id.ibtnSaveContactKeypad);
		
		// Set id for Call detail
		btnCreateContactFromDetail 	= (Button) findViewById(R.id.btnCreateContactFromDetail);
		btnUpdateContactFromDetail 	= (Button) findViewById(R.id.btnUpdateContactFromDetail);
		imgStatusCallDetail			= (ImageView) findViewById(R.id.imgStatusCallDetail);
		imgCallFromDetail			= (ImageView) findViewById(R.id.imgCallFromDetail); 
		linearSendSmsFromDetail		= (LinearLayout) findViewById(R.id.linearSendSmsFromDetail); 
		linearCallFromDetail		= (LinearLayout) findViewById(R.id.linearCallFromDetail);
		tvTimeCallDetail			= (TextView) findViewById(R.id.tvTimeCallDetail);
		tvDateCallDetail			= (TextView) findViewById(R.id.tvDateCallDetail);

		// set id for fake call
		edtAppFakeName = (EditText) findViewById(R.id.edtAppFakeName);
		imgCheckNameFake = (ImageView) findViewById(R.id.imgCheckNameFake);
		grdListIconFake = (GridView) findViewById(R.id.grdListIconFake);
		
		// set id for choose contact to update
		// Set ID for contact list form
		edtContactSecretFilterUpdate = (EditText) findViewById(R.id.edtContactSecretFilterUpdate);
		lvContactSecretUpdate = (ListView) findViewById(R.id.lvContactSecretUpdate);
		
	}

	/**
	 * Init value of activity
	 */
	void init() {
		db = new DatabaseHandler(context);
		mFlagCalling = FLAG_NOT_CALL;
		mPhoneNumberCalling = "";
		isCreateNew = false;
		imgContactsShow.setBackgroundColor(Color.parseColor("#AF3345"));
		initViewFlipper();
		initSlidingMenu();
		initUserID();
		initListContact();
		initTabhost();
		//initCreateNewContactForm();
		//initSettingForm();
	}

	/**
	 * Init User ID
	 */
	void initUserID() {
		ToolsSaveFile tsf = new ToolsSaveFile();

		String id_loggedin = tsf.LoadContentFile(context,
				ConstantsFileName.FILE_ID_LOG_IN);
		Log.e(TAG , "ID_LOGIN = "+ id_loggedin);
		int id = -1;
		if (id_loggedin == null || id_loggedin.equals("")
				|| id_loggedin.length() == 0) {

			id = -1;
		} else {
			try {
				id = Integer.parseInt(id_loggedin);

			} catch (Exception e) {
				id = -1;
				e.printStackTrace();
			}
		}
		USER_ID = id;
	}

	/**
	 * init for sliding panel
	 */
	void initSlidingMenu(){
		adapterSliding = new AdapterSlidingMenu(context);
		lvSlidingMenu.setAdapter(adapterSliding);
	}
	
	/**
	 * Init main flipper
	 */
	void initViewFlipper() {
		// init animation
		slide_in_left = AnimationUtils.loadAnimation(this,
				android.R.anim.slide_in_left);
		slide_out_right = AnimationUtils.loadAnimation(this,
				android.R.anim.slide_out_right);

		vflipMain.setInAnimation(slide_in_left);
		vflipMain.setOutAnimation(slide_out_right);
	}

	/**
	 * init List Contact
	 */
	void initListContact() {
		listContact = db.getAllContacts(USER_ID);
		
		if(listContact!=null && !listContact.equals(null) && listContact.size()>0){
			listContactSecretFilter = new ArrayList<DatabaseContact>();
			for(int i = 0 ; i < listContact.size(); i++){
				listContactSecretFilter.add(listContact.get(i));
			}
		}else{
			ControlsSyncSecretContact taskSync = new ControlsSyncSecretContact(context);
			taskSync.execute(null,null,null);
		}
		
		adapterSecretContacts = new AdapterSecretContacts(context,
				R.layout.item_search_notfound, listContact);
		lvContactSecret.setAdapter(adapterSecretContacts);
	}

	/**
	 * init List Contact Update
	 */
	void initListContactUpdate() {
		listContact = db.getAllContacts(USER_ID);
		
		if(listContact!=null && !listContact.equals(null) && listContact.size()>0){
			listContactSecretFilter = new ArrayList<DatabaseContact>();
			for(int i = 0 ; i < listContact.size(); i++){
				listContactSecretFilter.add(listContact.get(i));
			}
		}
		
		adapterSecretContacts = new AdapterSecretContacts(context,
				R.layout.item_search_notfound, listContact);
		adapterSecretContacts.setMode(1);
		lvContactSecretUpdate.setAdapter(adapterSecretContacts);
	}

	
	/**
	 * init Contact Profile
	 */
	void initContactProfile() {
		if (mContact != null) {
			if (mContact.getAvatar() != null
					&& mContact.getAvatar().length() > 5) {
				File imgFile = new File(mContact.getAvatar());
				Bitmap bm = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
				if (bm != null) {
					imgAvatarContact.setImageBitmap(bm);
				} else {
					imgAvatarContact.setImageResource(R.drawable.ic_contact);
				}

			} else {
				imgAvatarContact.setImageResource(R.drawable.ic_contact);
			}

			if (mContact.getLastCall() != null
					&& mContact.getLastCall().length() > 5) {
				tvLatestCall.setText(mContact.getLastCall());
			} else {
				tvLatestCall.setText(getResources()
						.getString(R.string.not_call));
			}

			if (mContact.getLastSms() != null
					&& mContact.getLastSms().length() > 5) {
				tvLatestsms.setText(mContact.getLastSms().substring(0, 16));
			} else {
				tvLatestsms.setText(getResources().getString(R.string.not_sms));
			}

			if (mContact.getIsSync() > 0) {
				tvSyncStatus
						.setText(getResources().getString(R.string.is_sync));
			} else {
				tvSyncStatus.setText(getResources()
						.getString(R.string.not_sync));
			}

			tvContactName.setText(mContact.getContactName());
			tvPhoneNumber.setText(mContact.getPhoneNumber());

		} else {
			imgAvatarContact.setImageResource(R.drawable.ic_contact);
			tvLatestCall.setText(getResources().getString(R.string.not_call));
			tvLatestsms.setText(getResources().getString(R.string.not_sms));
			tvSyncStatus.setText(getResources().getString(R.string.not_sync));
			tvContactName.setText(getResources().getString(
					R.string.contact_name));
			tvPhoneNumber.setText(getResources().getString(R.string.phone_num));
		}
	}

	/**
	 * init Create New Contact Form()
	 */
	void initCreateNewContactForm() {

		if (mContact != null) {
			Boolean contact_null = (mContact != null);
			Boolean name_length_null = contact_null
					&& (mContact.getContactName() != null)
					&& (!mContact.getContactName().equals(null))
					&& (mContact.getContactName().length() > 0);
			Boolean phone_length_null = contact_null
					&& (mContact.getPhoneNumber() != null)
					&& (!mContact.getPhoneNumber().equals(null))
					&& (mContact.getPhoneNumber().length() > 0);
			Boolean avatar_null = contact_null
					&& (mContact.getAvatar() != null)
					&& (!mContact.getAvatar().equals(null))
					&& (mContact.getAvatar().length() > 3);
			if (name_length_null) {
				edtEditContactName.setText(mContact.getContactName());
			} else {
				edtEditContactName.setText("");
			}

			if (phone_length_null) {
				edtEditPhoneNumber.setText(mContact.getPhoneNumber());
			} else {
				edtEditPhoneNumber.setText("");
			}

			if (avatar_null) {
				edtAvatarPath.setText(mContact.getAvatar());
				try {
					File imgFile = new File(mContact.getAvatar());
					Bitmap bm = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
					
				    // "RECREATE" THE NEW BITMAP
				    
					if (bm != null) {
						Log.e(TAG , "bm khac null");
						Bitmap resizedBitmap = Bitmap.createScaledBitmap(bm , 100, 100, false);
						imgChangeAvatarEdit.setImageBitmap(resizedBitmap);
					} else {
						Log.e(TAG , "bm null");
						imgChangeAvatarEdit.setImageResource(R.drawable.ic_contact);
					}
					
				} catch (Exception e) {
					e.printStackTrace();
				}
			} else {
				edtAvatarPath.setText("");
			}
			
			
			
		} else {
			edtEditContactName.setText("");
			edtEditPhoneNumber.setText("");
			edtAvatarPath.setText("");
		}
	}
	
	/**
	 * Init for fake app
	 */
	void initFakeApp(){
		
		ToolsSaveFile tsf = new ToolsSaveFile();
		String old_name = tsf.LoadContentFile(context, ConstantsFileName.FILE_NAME_OLD_SHORTCUT);
		edtAppFakeName.setText(old_name);
		
		adapterFakeIcon = new AdapterFakeIcon(context, R.layout.item_search_notfound);
		grdListIconFake.setAdapter(adapterFakeIcon);
		grdListIconFake.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				if(adapterFakeIcon.getSelectedPosition() == -1){
					grdListIconFake.setItemChecked(position, true);
					adapterFakeIcon.setSelectedPosition(position);
				}else if(adapterFakeIcon.getSelectedPosition()== position){
					grdListIconFake.setItemChecked(position, false);
					adapterFakeIcon.setSelectedPosition(-1);
				}else{
					grdListIconFake.setItemChecked(adapterFakeIcon.getSelectedPosition(), false);
					adapterFakeIcon.setSelectedPosition(position);
					grdListIconFake.setItemChecked(position, true);
				}
				adapterFakeIcon.notifyDataSetChanged();
			}
		} );
	}

	/**
	 * Init for call or sms form
	 * @param mode
	 * 1- call
	 * 2- sms
	 */
	void initListCallForm(final int mode_show){
		mode_history = mode_show;
		
		// Init List
		if(mode_show == 1){
			
			ArrayList<DatabaseCall> listEvent = new ArrayList<DatabaseCall>();
			listEvent = db.getListCall();
			if(listEvent != null && !listEvent.equals(null) && listEvent.size() > 0 ){
				String first_day = listEvent.get(0).getDate().substring(0, 10);
				listEvent.get(0).setIsFirstCallOfDay(true);
				for(int i = 1 ; i < listEvent.size() ; i ++){
					if(!listEvent.get(i).getDate().substring(0, 10).equals(first_day) ){
						first_day = listEvent.get(i).getDate().substring(0, 10);
						listEvent.get(i).setIsFirstCallOfDay(true);
					}
					Log.e(TAG ,"-i:" +listEvent.get(i).getPhone() + " " + listEvent.get(i).getContact_id());
				}
				
			}
			
			final AdapterCallLog adapter = new AdapterCallLog(context, R.layout.item_search_notfound, listEvent);
			adapter.setMode_load(mode_show);
			lvListCallLog.setAdapter(adapter);
			if(listEvent.size() > 0){
				lvListCallLog.setOnItemClickListener(new OnItemClickListener() {

					@Override
					public void onItemClick(AdapterView<?> parent, View view,
							int position, long id) {
						
						if(mode_show == 1 ){
							if(adapter.getItem(position).getContact_id() == -1){
								initForCallDetail(adapter.getItem(position));
								selectPage(9);
							}else{
								mContact = db.getContact( (int) adapter.getItem(position).getContact_id(), USER_ID);
								
								try{
									Log.e(TAG , mContact.toJSONString());
								}catch(Exception e){
									mContact = db.getContactLikePhoneNumber(adapter.getItem(position).getPhone(), USER_ID);
								}								
								
								selectPage(1);
							}
							
						}
					}
				});
			}
			
		}else if(mode_show == 2){
			
			listLastEvent = new ArrayList<DatabaseContact>();
			for(int i = 0 ; i < listContact.size();i++){
				if(ToolsSaveFile.checkStringNotNull(listContact.get(i).getLastSms(), 5)){
					listLastEvent.add(listContact.get(i));
				}
			}
			AdapterSmsList adapter = new AdapterSmsList(context, R.layout.item_search_notfound, listLastEvent);
			adapter.setMode_load(mode_show);
			lvListCall.setAdapter(adapter);
			lvListCall.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> parent, View view,
						int position, long id) {
					if(listLastEvent==null || listLastEvent.equals(null) || listLastEvent.size()==0){
						return;
					}
					if(mode_show == 1 ){
						mPhoneNumberCalling = listLastEvent.get(position).getPhoneNumber();
						mFlagCalling = FLAG_CALLING;
						ControlPhoneAction.makeCall(context, mPhoneNumberCalling);
					}else if(mode_show== 2){
						mContact = ((AdapterSmsList)parent.getAdapter()).getItem(position);
						selectPage(6);
					}
				}
			});
		}
		
	}
	
	/**
	 * Init list chat sms
	 */
	void initListChatSms(){
		listChatSms = db.getListSMS(mContact.getPrimaryKey());
		adapterSms= new AdapterChatSms(context, R.layout.item_search_notfound, listChatSms);
		adapterSms.setContact(mContact);
		lvListChat.setAdapter(adapterSms);
		lvListChat.setSelection(adapterSms.getCount() - 1);
	}
	
	/**
	 * Init tab host
	 */
	void initTabhost(){
//		imgHistorySmsShow.setImageResource(R.drawable.ic_x4);
//		imgHistoryCallShow.setImageResource(R.drawable.ic_x2);
//		imgContactsShow.setImageResource(R.drawable.ic_x0);
	}
	
	/**
	 * Init for call detail
	 */
	void initForCallDetail(DatabaseCall callProfile){
		mCallProfile = callProfile;
		mContact = new DatabaseContact();
		mContact.setPhoneNumber(callProfile.getPhone());		
		SimpleDateFormat sdf = new SimpleDateFormat(
				"yyyy/MM/dd HH:mm:ss", java.util.Locale.getDefault());
		String last_call = sdf.format(new Date());
		if(last_call.substring(0,10).equals(callProfile.getDate().substring(0, 10))){
			tvDateCallDetail.setText("Today");
		}else{
			tvDateCallDetail.setText(callProfile.getDate().substring(0, 10));
		}
		tvTimeCallDetail.setText(callProfile.getDate().substring(10, 16));
		
	}
	
	/**
	 * set functions for control in this activity
	 */
	void setFunctionForControls() {
		setFunctionForControlsInContacsListForm();
		setFunctionForControlsInContactProfileForm();
		setFunctionForControlsInSendSMSForm();
		setFunctionForControlsInCreateContactForm();
		setFunctionForControlsInSettingsForm();
		setFunctionForSlidingMenu();
		setFunctionForListChatSms();
		setFunctionForTabhost();
		setFunctionForPageKeyPad();
		setFunctionForCallDetail();
		setFunctionForFakeApp();
		setFunctionForControlsInContacsListUpdateForm();
	}
	
	/**
	 * set function for fake app
	 */
	void setFunctionForFakeApp(){
		edtAppFakeName.addTextChangedListener(new TextWatcher() {
			
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				
			}
			
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				
			}
			
			@Override
			public void afterTextChanged(Editable s) {
				if(s.toString().length() < 5 && s.length()>30){
					imgCheckNameFake.setImageResource(R.drawable.ic_fail);
				}else{
					imgCheckNameFake.setImageResource(R.drawable.ic_correct);
				}
			}
		});
		
		grdListIconFake.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
								
			}
		});
	
	}
	
	/**
	 * Set Function for call detail
	 */
	void setFunctionForCallDetail(){
		btnCreateContactFromDetail.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				selectPage(3);
			}
		});
		btnUpdateContactFromDetail.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				initListContactUpdate();
				selectPage(11);
			}
		});
		
		imgCallFromDetail.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {	
				mPhoneNumberCalling = mContact.getPhoneNumber();
				mFlagCalling = FLAG_CALLING;
				ListenerPhoneState.isInAppDelete = true;
				ListenerPhoneState.phone_number =  mPhoneNumberCalling;
				ControlPhoneAction.makeCall(context,
						mContact.getPhoneNumber());
			}
		});
		
		linearSendSmsFromDetail.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				
				selectPage(2);
				edtPhoneToSendSms.setText(mContact.getPhoneNumber());
			}
		});
		
		linearCallFromDetail.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {	
				mPhoneNumberCalling = mContact.getPhoneNumber();
				mFlagCalling = FLAG_CALLING;
				ListenerPhoneState.isInAppDelete = true;
				ListenerPhoneState.phone_number =  mPhoneNumberCalling;
				ControlPhoneAction.makeCall(context,
						mContact.getPhoneNumber());
			}
		});
	}

	
	/**
	 * Set Function For Controls In Contacs List Form
	 */
	void setFunctionForControlsInContacsListForm() {
		edtContactSecretFilter.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {

			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {

			}

			@Override
			public void afterTextChanged(Editable s) {
				filterListview(s.toString());

			}
		});

		lvContactSecret.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				
				if (listContactSecretFilter == null
						|| listContactSecretFilter.size() == 0) {
					return;
				}
				
				mContact = ((AdapterSecretContacts) parent.getAdapter())
						.getItem(position);
				Log.e(TAG, "info contact "+ mContact.toJSONString());
				selectPage(1);
			}
		});
	}

	/**
	 * Set Function For Controls In Contacs List Update
	 */
	void setFunctionForControlsInContacsListUpdateForm() {
		edtContactSecretFilterUpdate.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {

			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {

			}

			@Override
			public void afterTextChanged(Editable s) {
				filterListviewUpdate(s.toString());

			}
		});

		lvContactSecretUpdate.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				
				if (listContactSecretFilter == null
						|| listContactSecretFilter.size() == 0) {
					return;
				}
				
				listContactSecretFilter.get(position).setPhoneNumber(mContact.getPhoneNumber());
				db.updateContact(listContactSecretFilter.get(position).getPrimaryKey(),
						listContactSecretFilter.get(position));
				mContact = listContactSecretFilter.get(position);
				selectPage(1);
				
			}
		});
	}

	
	/**
	 * Set Function for control in contact profile form
	 */
	void setFunctionForControlsInContactProfileForm() {
		btnCallContact.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (mContact != null && mContact.getPhoneNumber() != null
						&& mContact.getPhoneNumber().length() > 3) {
					mPhoneNumberCalling = mContact.getPhoneNumber();
					mFlagCalling = FLAG_CALLING;
					ListenerPhoneState.isInAppDelete = true;
					ListenerPhoneState.phone_number =  mPhoneNumberCalling;
					ControlPhoneAction.makeCall(context,
							mContact.getPhoneNumber());
				}

			}
		});

		btnSendMessage.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				//selectPage(2);
				selectPage(6);
			}
		});
	
		btnDelete.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				OnClickListener listenerDeleteContact = new OnClickListener() {
					
					@Override
					public void onClick(View v) {
						
						if(mContact.get_Id() <= 0){
							try{
								db.deleteContact(mContact.getPrimaryKey());
							}catch(Exception e){
								e.printStackTrace();
							}finally{
								mAlertDialog = new ViewAlertDialogManager();
								mAlertDialog.showAlertDialog(context, "Success !",
										"Contact has been remove!",
										false);
								initListContact();
								selectPage(0);
							}
							
							
							return;
						}
						
						ConnectionDetector cd = new ConnectionDetector(context);
						if(!cd.isConnectingToInternet()){
							mAlertDialog = new ViewAlertDialogManager();
							mAlertDialog.showAlertDialog(context, "Internet error !",
									"Please connect to an internet network",
									false);
						}
						
						DeleteContact taskDeleteContact = new DeleteContact(mContact);
						taskDeleteContact.execute(null,null,null);
						
					}
				};
				
				ViewDialog deleteDialog = new ViewDialog(context, "Delete Contact", "Do you want to delete this contact", listenerDeleteContact, null);
				deleteDialog.showDialog();
			}
		});
		btnEdit.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				isCreateNew = false;
				selectPage(3);
			}
		});
		
		linearShowSMS.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				initListCallForm(2);
				selectPage(5);
			}
		});
		
		linearShowCall.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				initListCallForm(1);
				selectPage(8);
			}
		});
	
	}

	/**
	 * Set Function for control in send sms form
	 */
	void setFunctionForControlsInSendSMSForm() {
		
		lvShowContactSendSms.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				if(listContactSecretFilter.size() >0){
					edtPhoneToSendSms.setText(listContactSecretFilter.get(position).getPhoneNumber());
				}
				
			}
		});
		
		btnSendSmsPageSendSms.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {

				String phoneNumber = edtPhoneToSendSms.getText().toString().trim();
				if( ToolsSaveFile.checkStringNotNull(phoneNumber)){
					if(ToolsSaveFile.checkStringNotNull(edtContentSMS.getText().toString().trim())){
						ControlPhoneAction.sendSMS(phoneNumber, edtContentSMS.getText().toString().trim());
						edtContentSMS.setText("");
						new Handler().postDelayed(new Runnable() {
							
							@Override
							public void run() {
				
								selectPage(0);
							}
						}, 800);
					}else{
						mAlertDialog = new ViewAlertDialogManager();
						mAlertDialog
						.showAlertDialog(
								context,
								"Please fill content of sms",
								"You must fill the content of sms.",
								false);
						
					}
					
				}else{
					mAlertDialog = new ViewAlertDialogManager();
					mAlertDialog
					.showAlertDialog(
							context,
							"Please fill phone number to send",
							"You must fill the phone number.",
							false);
				}
			}
		});
		
		btnClearContentSms.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {

				edtContentSMS.setText("");
			}
		});
		
		edtPhoneToSendSms.addTextChangedListener(new TextWatcher() {
			
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {

				
			}
			
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {

				
			}
			
			@Override
			public void afterTextChanged(Editable s) {
				String filterString = s.toString().trim();
				if(ToolsSaveFile.checkStringNotNull(filterString)){
					lvShowContactSendSms.setVisibility(View.VISIBLE);
				}else{
					lvShowContactSendSms.setVisibility(View.GONE);
					return;
				}
				listContactSecretFilter = new ArrayList<DatabaseContact>();
				for (int i = 0; i < listContact.size(); i++) {
					if (listContact.get(i).getPhoneNumber()
							.contains(filterString.trim())) {
						listContactSecretFilter.add(listContact.get(i));
					}
				}
				adapterSecretContacts = new AdapterSecretContacts(context,
						R.layout.item_search_notfound, listContactSecretFilter);
				adapterSecretContacts.setMode(1);
				lvShowContactSendSms.setAdapter(adapterSecretContacts);
				
			}
		});
		
		edtContentSMS.addTextChangedListener(new TextWatcher() {
			
			String old_text;
			
			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				old_text = s.toString();
			}

			@Override
			public void afterTextChanged(Editable s) {
				if (s.toString().length() > 0) {
					int num = 160 - s.toString().trim().length();
					if(num<0){
						num = 0;
						edtContentSMS.setText(old_text);					
					}
					tvNumberCharacter.setText(" " + num + " ");
				} else {
					tvNumberCharacter.setText("");
				}

			}
		});
	}

	/**
	 * set Function For Controls InCreate Contact Form
	 */
	void setFunctionForControlsInCreateContactForm() {
		
		
		OnClickListener changeAvatarClick = new OnClickListener() {

			@Override
			public void onClick(View v) {
				try {
					Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
					intent.setType("image/*");
					startActivityForResult(intent, PICKFILE_RESULT_CODE);
				} catch (ActivityNotFoundException exp) {
					Toast.makeText(
							getBaseContext(),
							"No File (Manager / Explorer)etc Found In Your Device",
							Toast.LENGTH_SHORT).show();
				}

			}
		};
		
		btnChooseAvatar.setOnClickListener(changeAvatarClick);
		
		imgChangeAvatarEdit.setOnClickListener(changeAvatarClick);

	}

	/**
	 * set Function For Controls In Settings Form
	 */
	void setFunctionForControlsInSettingsForm() {
		// show linear change password
		linearShowChangePassword.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				showHideLinearSettingContent(1);
			}
		});

		// show linear change security key
		linearShowChangeSecurityKey.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				showHideLinearSettingContent(2);
			}
		});
		
		linearRateApp.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				showAppOnPlayStore();
				
			}
		});
		
		linearSignOut.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {

				ToolsSaveFile tsf = new ToolsSaveFile();
				tsf.SaveContentFile(context, ConstantsFileName.FILE_ID_LOG_IN, "");
				Intent intent = new Intent(ActivityContactList.this,
						ActivityLogin.class);
				startActivity(intent);
				finish();
			}
		});
		
		linearOtherApp.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				openCompanyPageOnPlayStore();
			}
		});
		
		linearShareApp.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				shareApp();
				
			}
		});
		
		linearAboutUs.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				aboutUs();
			}
		});
		
		linearFakeApp.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				initFakeApp();
				selectPage(10);
			}
		});
		
//		edtSettingOldPassword, edtSettingPassword, edtSettingRePassword,
//		edtSettingSecurityKey, edtSettingReSecurityKey;
		
		// save new password
		btnPasswordSave.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				
				ConnectionDetector cd = new ConnectionDetector(context);
				if(!cd.isConnectingToInternet()){
					mAlertDialog = new ViewAlertDialogManager();
					mAlertDialog
							.showAlertDialog(
									context,
									"Network error!",
									"Your phone must connect to an internet network to change password.",
									false);
					return;
				}
				
				if (edtSettingOldPassword.getText().toString().length() < 6) {
					mAlertDialog = new ViewAlertDialogManager();
					mAlertDialog
							.showAlertDialog(
									context,
									"Password error!",
									"Password length must be more than 6 character length",
									false);
					return;
				}

				if (edtSettingOldPassword.getText().toString().length() >= 30) {
					mAlertDialog = new ViewAlertDialogManager();
					mAlertDialog
							.showAlertDialog(
									context,
									"Password error!",
									"Password length must be less than 30 character length",
									false);
					return;
				}
				
				if (edtSettingPassword.getText().toString().length() < 6) {
					mAlertDialog = new ViewAlertDialogManager();
					mAlertDialog
							.showAlertDialog(
									context,
									"Password error!",
									"Password length must be more than 6 character length",
									false);
					return;
				}

				if (edtSettingPassword.getText().toString().length() >= 30) {
					mAlertDialog = new ViewAlertDialogManager();
					mAlertDialog
							.showAlertDialog(
									context,
									"Password error!",
									"Password length must be less than 30 character length",
									false);
					return;
				}

				if (!edtSettingPassword.getText().toString()
						.equals(edtSettingRePassword.getText().toString())) {
					mAlertDialog = new ViewAlertDialogManager();
					mAlertDialog.showAlertDialog(context, "Password error!",
							"re-enter the password and password do not match",
							false);
					return;
				}
				
				String old_pass = edtSettingOldPassword.getText().toString().trim();
				
				String new_pass = edtSettingRePassword.getText().toString().trim();
				
				ChangePassword taskChangePassword = new ChangePassword(old_pass, new_pass);
				taskChangePassword.execute(null,null,null);
			}
		});
		
		// save new security key
		btnSecurityKeySave.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				ConnectionDetector cd = new ConnectionDetector(context);
				if(!cd.isConnectingToInternet()){
					mAlertDialog = new ViewAlertDialogManager();
					mAlertDialog
							.showAlertDialog(
									context,
									"Network error!",
									"Your phone must connect to an internet network to change password.",
									false);
					return;
				}
				
				if (edtSettingSecurityKey.getText().toString().length() !=4) {
					mAlertDialog = new ViewAlertDialogManager();
					mAlertDialog
							.showAlertDialog(
									context,
									"Security key error!",
									"Security key length must be 4 character length",
									false);
					return;
				}

				if (edtSettingReSecurityKey.getText().toString().length() !=4) {
					mAlertDialog = new ViewAlertDialogManager();
					mAlertDialog
							.showAlertDialog(
									context,
									"Security key error!",
									"Security key length must be 4 character length",
									false);
					return;
				}

				if (!edtSettingSecurityKey.getText().toString()
						.equals(edtSettingReSecurityKey.getText().toString())) {
					mAlertDialog = new ViewAlertDialogManager();
					mAlertDialog.showAlertDialog(context, "Security key error!",
							"re-enter the Security key and Security key do not match",
							false);
					return;
				}
				
				ChangeSecurityKey taskChangeSecurityKey = new ChangeSecurityKey(edtSettingSecurityKey.getText().toString().trim());
				taskChangeSecurityKey.execute(null,null,null);
				
			}
		});
	
	}
	
	/**
	 * Set Function for all item in sliding menu
	 */
	void setFunctionForSlidingMenu(){
		
		lvSlidingMenu.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				if(!isExpanded){
					return;
				}
				switch (position) {
				case 0:
					showHideLinearSettingContent(0);
					selectPage(4);	
					break;
				case 1:
					if(mode!= 0){
						selectPage(0);
					}else{
						if(isExpanded){
							interstitial.show();
							//openMenuSliding();
						}
					}
					break;
//				case 2:
//					initListCallForm(1);
//					selectPage(5);
//					break;
//				case 3:
//					initListCallForm(2);
//					selectPage(5);
//					break;
//				case 4:
				case 2:
					// lam sau khi up len play store
//					Uri uri = Uri.parse("market://details?id="
//							+ context.getPackageName());
					showAppOnPlayStore();
				default:
					break;
				}
			}
		});
		
		btnLogout.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if(!isExpanded){
					return;
				}
				ToolsSaveFile tsf = new ToolsSaveFile();
				tsf.SaveContentFile(context, ConstantsFileName.FILE_ID_LOG_IN, "");
				Intent intent = new Intent(ActivityContactList.this,
						ActivityLogin.class);
				startActivity(intent);
				finish();
				
			}
		});
	}
	
	/**
	 * Set Function for control in list chat sms form
	 */
	void setFunctionForListChatSms(){
		btnSmsSubmit.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if(mContact == null || mContact.equals(null) || mContact.getPhoneNumber().length() < 2){
					return;
				}
				
				if( edtSmsContentSubmit.getText().toString().length()<1){
					return;
				}
				
				if(edtSmsContentSubmit.getText().toString().length()>150 ){
					mAlertDialog = new ViewAlertDialogManager();
					mAlertDialog.showAlertDialog(context, "Sms so long", "Max size of content message is 160 character.", false);
				}
				
				TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);  //gets the current TelephonyManager
				if (tm.getSimState() == TelephonyManager.SIM_STATE_ABSENT){
					// the phone has a sim card
					return;
				}
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss",java.util.Locale.getDefault());
				String last_sms = sdf.format(new Date());
				DatabaseSMS sms_new_item = new DatabaseSMS(mContact.getPrimaryKey(), mContact.getPhoneNumber(), edtSmsContentSubmit.getText().toString(), DatabaseSMS.SEND);
				sms_new_item.setDate(last_sms);
				
				try{
					ControlPhoneAction.sendSMS(mContact.getPhoneNumber(), edtSmsContentSubmit.getText().toString());
					db.addNewSMS(sms_new_item);
				}catch(Exception e){
					
				}finally{
					
					mContact.setLastSms(last_sms + edtSmsContentSubmit.getText().toString());
					db.updateContactLastSms(mContact.getPrimaryKey(), mContact);
					listChatSms.add(sms_new_item);
					edtSmsContentSubmit.setText("");
					adapterSms = new AdapterChatSms(context, R.layout.item_search_notfound, listChatSms);
					lvListChat.setAdapter(adapterSms);
					lvListChat.setSelection(adapterSms.getCount() - 1);
				}
				
				
				
			}
		});
		
		
		imgChooseImageForMMS.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				sendMMS(mContact.getPhoneNumber(), "chym chich bong", "path");
			}
		});
	}
	
	/**
	 * Set function for the tabhost
	 */
	void setFunctionForTabhost(){
		imgHistorySmsShow.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if(mode==5 && mode_history == 2){
					return;
				}
				initListCallForm(2);
				selectPage(5);
			}
		});
		imgHistoryCallShow.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if(mode==5 && mode_history == 1){
					return;
				}
				initListCallForm(1);
				selectPage(8);
			}
		});
		imgContactsShow.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if(mode==0){
					return;
				}
				selectPage(0);
				
			}
		});
		imgSettingShow.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if(mode == 4){
					return;
				}
				selectPage(4);
			}
		});
		
		imgKeypadShow.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if(mode == 7){
					return;
				}
				selectPage(7);
			}
		});
		
	}
	
	/**
	 * List view shot result if true with filter string
	 * 
	 * @param filterString
	 */
	void filterListview(String filterString) {
		if(listContact==null|| listContact.equals(null)||listContact.size()==0){
			return;
		}
		listContactSecretFilter = new ArrayList<DatabaseContact>();
		for (int i = 0; i < listContact.size(); i++) {
			if (listContact.get(i).getContactName()
					.contains(filterString.trim())) {
				listContactSecretFilter.add(listContact.get(i));
			}
		}
		adapterSecretContacts = new AdapterSecretContacts(context,
				R.layout.item_search_notfound, listContactSecretFilter);
		lvContactSecret.setAdapter(adapterSecretContacts);
	}
	
	/**
	 * List view shot result if true with filter string
	 * 
	 * @param filterString
	 */
	void filterListviewUpdate(String filterString) {
		if(listContact==null|| listContact.equals(null)||listContact.size()==0){
			return;
		}
		listContactSecretFilter = new ArrayList<DatabaseContact>();
		for (int i = 0; i < listContact.size(); i++) {
			if (listContact.get(i).getContactName()
					.contains(filterString.trim())) {
				listContactSecretFilter.add(listContact.get(i));
			}
		}
		adapterSecretContacts = new AdapterSecretContacts(context,
				R.layout.item_search_notfound, listContactSecretFilter);
		adapterSecretContacts.setMode(1);
		lvContactSecretUpdate.setAdapter(adapterSecretContacts);
	}

	/**
	 * Select page of main flipper
	 * 
	 * @param page
	 *            : 
	 *            0 - contact list 
	 *            1 - contact profile 
	 *            2 - send sms 
	 *            3 - create or edit contacts 
	 *            4 - settings
	 *            5 - List History Call or SMS
	 *            6 - Chat log 
	 *            7 - Keypad
	 *            8 - Call log
	 *            9 - Call detail
	 *            10 - Fake app
	 *            11 - Update contact list from detail
	 */
	void selectPage(int page) {
		
		if(isExpanded){
			openMenuSliding();
		}
		
		getActionBar().setDisplayHomeAsUpEnabled(false);
		
		InputMethodManager imm = (InputMethodManager)getSystemService(
				Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
		mode = page;
		String title_name = "";

		mniActionNewContact.setVisible(false);
		mniActionSendSMS.setVisible(false);
		mniActionSaveContact.setVisible(false);
		mniActionMoveToTrash.setVisible(false);
		
		// set default color
		imgHistorySmsShow.setBackgroundColor(color.transparent);
		imgHistoryCallShow.setBackgroundColor(color.transparent);
		imgContactsShow.setBackgroundColor(color.transparent);
		imgSettingShow.setBackgroundColor(color.transparent);
		imgKeypadShow.setBackgroundColor(color.transparent);
		
//		linearTabhost.setVisibility(View.GONE);
		
		switch (page) {
		case 0:
			imgContactsShow.setBackgroundColor(Color.parseColor("#AF3345"));
			getActionBar()
					.setLogo(getResources().getDrawable(R.drawable.ic_tab_contact));
			mniActionNewContact.setVisible(true);
			linearTabhost.setVisibility(View.VISIBLE);
			title_name = getResources().getString(R.string.title_contact_list);
			break;
		case 1:
			imgContactsShow.setBackgroundColor(Color.parseColor("#AF3345"));
			getActionBar().setDisplayHomeAsUpEnabled(true);
			getActionBar()
					.setLogo(getResources().getDrawable(R.drawable.ic_tab_contact));
			
			title_name = getResources().getString(
					R.string.title_contact_profile);
			initContactProfile();
			break;
		case 2:
			imgHistorySmsShow.setBackgroundColor(Color.parseColor("#AF3345"));
			edtPhoneToSendSms.setText("");
			getActionBar().setDisplayHomeAsUpEnabled(true);
			getActionBar()
					.setLogo(getResources().getDrawable(R.drawable.ic_home));
//			mniActionSendSMS.setVisible(true);
			
			title_name = getResources().getString(R.string.title_send_sms);
//			if (mContact != null && mContact.getContactName() != null
//					&& mContact.getContactName().length() > 3) {
//				title_name = title_name + " to: " + mContact.getContactName();
//			}
			break;
		case 3:
			imgContactsShow.setBackgroundColor(Color.parseColor("#AF3345"));
			getActionBar().setDisplayHomeAsUpEnabled(true);
			getActionBar()
					.setLogo(getResources().getDrawable(R.drawable.ic_home));
			mniActionSaveContact.setVisible(true);
			initCreateNewContactForm();
			linearTabhost.setVisibility(View.VISIBLE);
			if (mContact != null && mContact.getContactName() != null
					&& mContact.getContactName().length() > 3) {
				title_name = getResources().getString(
						R.string.title_edit_contact)
						+ " " + mContact.getContactName();
			} else {
				title_name = getResources().getString(
						R.string.title_create_contact);
			}
			break;
		case 4:
			imgSettingShow.setBackgroundColor(Color.parseColor("#AF3345"));
			getActionBar().setDisplayHomeAsUpEnabled(true);
			getActionBar()
					.setLogo(getResources().getDrawable(R.drawable.ic_tab_setting));
			title_name = getResources().getString(R.string.action_settings);
			showHideLinearSettingContent(0);	
			break;
		case 5:
			imgHistorySmsShow.setBackgroundColor(Color.parseColor("#AF3345"));
			getActionBar()
			.setLogo(getResources().getDrawable(R.drawable.ic_tab_sms));
			linearTabhost.setVisibility(View.VISIBLE);
			if(mode_history==1){
				title_name = getResources().getString(R.string.title_call_list);
			}else{
				title_name = getResources().getString(R.string.title_sms_list);
				mniActionSendSMS.setVisible(true);
			}
			break;
		case 6:
			imgHistorySmsShow.setBackgroundColor(Color.parseColor("#AF3345"));
			getActionBar().setDisplayHomeAsUpEnabled(true);
			getActionBar()
			.setLogo(getResources().getDrawable(R.drawable.ic_tab_sms));
			initListChatSms();
			title_name = mContact.getContactName();
			break;
		case 7:
			imgKeypadShow.setBackgroundColor(Color.parseColor("#AF3345"));
			title_name = getResources().getString(R.string.dial);
			getActionBar()
			.setLogo(getResources().getDrawable(R.drawable.ic_tab_keypad));
			initForKeypadPage();
			break;
		case 8:
			imgHistoryCallShow.setBackgroundColor(Color.parseColor("#AF3345"));
			getActionBar()
			.setLogo(getResources().getDrawable(R.drawable.ic_tab_recent));
			title_name = getResources().getString(R.string.title_call_list);
			linearTabhost.setVisibility(View.VISIBLE);
			break;
		case 9:
			title_name = mContact.getPhoneNumber();
			getActionBar().setDisplayHomeAsUpEnabled(true);
			mniActionMoveToTrash.setVisible(true);
			break;
		case 10:
			title_name = getResources().getString(R.string.title_fake_app);
			getActionBar().setDisplayHomeAsUpEnabled(true);
			getActionBar()
			.setLogo(getResources().getDrawable(R.drawable.ic_fake_app_white));
			mniActionSaveContact.setVisible(true);
			break;
		case 11:
			title_name = getResources().getString(R.string.title_choose_contact_update);
			getActionBar().setDisplayHomeAsUpEnabled(true);
			break;
		}
		vflipMain.setDisplayedChild(page);
		this.getActionBar().setTitle(title_name);
		System.gc();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (data == null)
			return;
		switch (requestCode) {
		case PICKFILE_RESULT_CODE:
			if (resultCode == RESULT_OK) {
				try {
					Uri selectedImage = data.getData();
					String path = ToolsImageHelper.getRealPathFromURI(context , selectedImage);
					edtAvatarPath.setText(path);
					File imgFile = new File(path);
					Bitmap bm = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
					
				    // CREATE A MATRIX FOR THE MANIPULATION
				    Matrix matrix = new Matrix();
				    // RESIZE THE BIT MAP
				    matrix.postScale(100, 100);

				    // "RECREATE" THE NEW BITMAP
				    
					if (bm != null) {
						Log.e(TAG , "bm khac null");
						Bitmap resizedBitmap = Bitmap.createScaledBitmap(bm , 100, 100, false);
						imgChangeAvatarEdit.setImageBitmap(resizedBitmap);
					} else {
						Log.e(TAG , "bm null");
						imgChangeAvatarEdit.setImageResource(R.drawable.ic_contact);
					}
					
				} catch (Exception e) {
					e.printStackTrace();
				}

			}
		}
	}

	@Override
	protected void onResume() {
		Log.e(TAG , "ON RESUME");
		
		switch (mFlagCalling) {
		case FLAG_CALLING:
			// delete call
			if(ToolsSaveFile.checkStringNotNull(mPhoneNumberCalling)){
				deleteAllCallFromPhoneNumber(mPhoneNumberCalling);
				mPhoneNumberCalling = "";
				mFlagCalling = FLAG_NOT_CALL;
			}			
			break;

		default:
			break;
		}
		
		super.onResume();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (db != null) {
			db.close();
		}
		unregisterReceiver(broadcastUpdateForm);
		System.gc();
	}

	/**
	 * Save Contact to contact list
	 * 
	 * @return true - save success false - save failed
	 */
	Boolean saveContactToContactList() {
		
		
		if (edtEditContactName.getText().toString().trim().length() < 2) {
			Log.e(TAG , "ten ngan qua");
			return false;
		}

		if (edtEditPhoneNumber.getText().toString().trim().length() < 5) {
			Log.e(TAG , "so ngan qua");
			return false;
		}

		if (mContact == null || mContact.equals(null)) {
			mContact = new DatabaseContact();
			mContact.set_User_Id(USER_ID);
		}

		mContact.setContactName(edtEditContactName.getText().toString().trim());
		mContact.setPhoneNumber(edtEditPhoneNumber.getText().toString().trim());

		if (edtAvatarPath.getText().toString().trim().length() > 5) {
			Log.e(TAG , "PATH = "+ edtAvatarPath.getText().toString());
			File imgFile = new File(edtAvatarPath.getText().toString().trim());
			Bitmap bm = ToolsImageHelper.decodeFile(imgFile , 80 , 80);
			if(bm!=null){
				Bitmap resizeBitmap = Bitmap.createScaledBitmap(bm , 100, 100, false);
				ToolsImageHelper.saveImageToApp(context, ToolsImageHelper.getRoundedCornerBitmap(resizeBitmap, 80), mContact.getContactName());
				resizeBitmap = null;
				bm = null;
				
			}			
			String path_file = getFilesDir().getPath().toString()+"/" + mContact.getContactName() +".jpg";
			mContact.setAvatar(path_file);
		}
		
		long result_add = 0;
		if (isCreateNew) {
			result_add = db.addContact(mContact);
		} else {
			mContact.setIsSync(-1);
			result_add = db.updateContact(mContact.getPrimaryKey() , mContact);
		}

		return result_add>0 ? true : false ;
	}
	
	/**
	 * Send sms
	 * - true: send success
	 * - false: send failed
	 */
	Boolean isSendSMSSuccess(){
		TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);  //gets the current TelephonyManager
		if (tm.getSimState() != TelephonyManager.SIM_STATE_ABSENT){
			// the phone has a sim card
			if(edtContentSMS.getText().toString().length() <1){
				return false;
			}else{
				ControlPhoneAction.sendSMS(mContact.getPhoneNumber(), edtContentSMS.getText().toString());
				edtContentSMS.setText("");
			}
		} else {
			// no sim card available
			return false;
		}		
		return true;
	}
	
	/**
	 * Delete all call from phone number after call
	 * @param phone_num
	 * phone number need to delete
	 */
	void deleteAllCallFromPhoneNumber(String phone_num){
		
		ContentResolver resolver = getBaseContext().getContentResolver();
		
		try
        {
            String strUriCalls = "content://call_log/calls";
            Uri UriCalls = Uri.parse(strUriCalls);
            //Cursor c = res.query(UriCalls, null, null, null, null);
            if(null != resolver)
            {
                resolver.delete(UriCalls,CallLog.Calls.NUMBER +"=?",new String[]{ phone_num});
            }
        }
        catch(Exception e) 
        { 
            e.printStackTrace();
        } 
	}
	
	void openMenuSliding(){
		if(!isExpanded){
    		isExpanded = true;   		    				        		
        	
    		//Expand
    		new AnimationExpand(linearSlidingPanel, panelWidth,
    	    Animation.RELATIVE_TO_SELF, 0.0f,
    	    Animation.RELATIVE_TO_SELF, 0.75f, 0, 0.0f, 0, 0.0f);		    			         	    
    	}else{
    		isExpanded = false;
    		
    		//Collapse
    		new AnimationCollapse(linearSlidingPanel,panelWidth,
    	    TranslateAnimation.RELATIVE_TO_SELF, 0.75f,
    	    TranslateAnimation.RELATIVE_TO_SELF, 0.0f, 0, 0.0f, 0, 0.0f);
   
			
    	}
	}
	
	class ChangePassword extends AsyncTask<Void, Void, Void>{
		
		List<NameValuePair> listPair;

		String result_from_server = "";

		ProgressDialog progressDialog = null;
		
		ChangePassword(String old_pass , String new_pass){
			listPair = new ArrayList<NameValuePair>();
			listPair.add(new BasicNameValuePair("user_id",
					Integer.toString(USER_ID)));
			listPair.add(new BasicNameValuePair(DatabaseUser.KEY_PASSWORD, old_pass));
			listPair.add(new BasicNameValuePair("newpassword", new_pass));
			
		}

		@Override
		protected Void doInBackground(Void... params) {
			HttpRequest request = new HttpRequest();
			result_from_server = request.makeServiceCall(
					ConstantsFileName.URL_USER_CHANGE_PASS, HttpRequest.POST,
					listPair);
			
			return null;
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			progressDialog = new ProgressDialog(context);
			progressDialog.setMessage("processing...");
			progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			progressDialog.setIndeterminate(true);

			progressDialog.show();
		}

		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			if (progressDialog != null) {
				progressDialog.dismiss();
			}

			if (result_from_server == null || result_from_server.equals(null)
					|| result_from_server.equals("")) {
				mAlertDialog = new ViewAlertDialogManager();
				mAlertDialog.showAlertDialog(context, "Request timeout !",
						"Something for work is incorrect ! Please try again !",
						false);
			} else {
				Log.e(TAG, result_from_server);
				try {
					JSONObject jsonObject = new JSONObject(result_from_server);
					int success = jsonObject
							.getInt(ConstantsFileName.success_field);

					if (success == 1) {
						mAlertDialog = new ViewAlertDialogManager();
						mAlertDialog.showAlertDialog(context, "Success !",
								"Your password was changed",
								false);
					}else{
						mAlertDialog = new ViewAlertDialogManager();
						mAlertDialog.showAlertDialog(context, "Failed !",
								"Your password was not changed becasue:"+ jsonObject
								.getString(ConstantsFileName.log_field),
								false);
					}
				}catch(Exception e){
					e.printStackTrace();
				}
			}
		}
		
	}
	
	class ChangeSecurityKey extends AsyncTask<Void, Void, Void>{
		
		List<NameValuePair> listPair;

		String result_from_server = "";

		ProgressDialog progressDialog = null;
		
		String security_key;
		
		ChangeSecurityKey(String security_key){
			this.security_key = security_key;
			listPair = new ArrayList<NameValuePair>();
			listPair.add(new BasicNameValuePair("user_id",
					Integer.toString(USER_ID)));
			listPair.add(new BasicNameValuePair(DatabaseUser.KEY_SECRET, security_key));
			Log.e(TAG , "secret key = "+ security_key+ " user_id="+USER_ID);
		}

		@Override
		protected Void doInBackground(Void... params) {
			HttpRequest request = new HttpRequest();
			result_from_server = request.makeServiceCall(
					ConstantsFileName.URL_USER_CHANGE_SECURITY, HttpRequest.POST,
					listPair);
			
			return null;
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			progressDialog = new ProgressDialog(context);
			progressDialog.setMessage("processing...");
			progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			progressDialog.setIndeterminate(true);

			progressDialog.show();
		}

		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			if (progressDialog != null) {
				progressDialog.dismiss();
			}

			if (result_from_server == null || result_from_server.equals(null)
					|| result_from_server.equals("")) {
				mAlertDialog = new ViewAlertDialogManager();
				mAlertDialog.showAlertDialog(context, "Request timeout !",
						"Something for work is incorrect ! Please try again !",
						false);
			} else {
				Log.e(TAG, result_from_server);
				try {
					JSONObject jsonObject = new JSONObject(result_from_server);
					int success = jsonObject
							.getInt(ConstantsFileName.success_field);

					if (success == 1) {
						mAlertDialog = new ViewAlertDialogManager();
						mAlertDialog.showAlertDialog(context, "Success !",
								"Your Security key was changed",
								false);
						
						// update user
						DatabaseUser user = db.getUser(USER_ID);
						user.setSecretKey(security_key);
						db.updateUser(user);
						
					}else{
						mAlertDialog = new ViewAlertDialogManager();
						mAlertDialog.showAlertDialog(context, "Failed !",
								"Your Security key was not changed becasue:"+ jsonObject
								.getString(ConstantsFileName.log_field),
								false);
					}
				}catch(Exception e){
					e.printStackTrace();
				}
			}
		}
		
	}
	
		
	/**
	 * Broadcast update view when have event
	 */
	final BroadcastReceiver broadcastUpdateForm = new BroadcastReceiver(){

		@Override
		public void onReceive(Context context, Intent intent) {
			Log.e(TAG , "NHAN DC EXTRA");
			Bundle bundleMessageData=intent.getExtras();
			if(bundleMessageData!=null){
				try{
					
					int flag = bundleMessageData.getInt(ConstantsFileName.TAG_GET_FLAG);
					
					switch (flag) {
					case ConstantsFileName.FLAG_RECEIVE_CALL:
						// check mode
						Log.e(TAG , " mode =" + mode + " ");
						Intent sercurityLog = new Intent(ActivityContactList.this,
								ActivityLogin.class);
						startActivity(sercurityLog);
						break;
					case ConstantsFileName.FLAG_RECEIVE_SMS:
						// check mode
						Log.e(TAG , " mode =" + mode + " ");
						listContact = db.getAllContacts(USER_ID);
						
						if(mode == 5 ){
							initListCallForm(2);
						}else if(mode == 6){
							if(listChatSms==null || listChatSms.equals(null)){
								listChatSms = new ArrayList<DatabaseSMS>();
							}
							if(adapterSms!=null || !adapterSms.equals(null) ){
								Log.e(TAG , "adapter != null");
								
								
								String phone_receive = bundleMessageData.getString(DatabaseContact.KEY_PHONE);

								if (mContact != null
										&& !mContact.equals(null)
										&& (mContact.getPhoneNumber().contains(
												phone_receive) || mContact
												.getPhoneNumber().contains(
														phone_receive
																.substring(3)))) {
									Log.e(TAG, "mContact != null");
									// get data from bundle
									String body = bundleMessageData
											.getString(DatabaseSMS.KEY_CONTENT);
									DatabaseSMS new_sms_item = new DatabaseSMS(
											mContact.getPrimaryKey(),
											phone_receive, body,
											DatabaseSMS.RECEIVE);
									SimpleDateFormat sdf = new SimpleDateFormat(
											"yyyy/MM/dd HH:mm:ss",
											java.util.Locale.getDefault());
									String last_call = sdf.format(new Date());
									new_sms_item.setDate(last_call);
									listChatSms.add(new_sms_item);
									adapterSms = new AdapterChatSms(context,
											R.layout.item_search_notfound,
											listChatSms);
									adapterSms.setContact(mContact);
									lvListChat.setAdapter(adapterSms);
									lvListChat.setSelection(adapterSms
											.getCount() - 1);
	}
								
							}
						}
						
						
						break;
					case ConstantsFileName.FLAG_UPDATE_FINISH:
						// check mode
						initListContact();
						break;
					default:
						break;
					}
				}catch(Exception e){
					e.printStackTrace();
				}
			}
		}
		
	};
	
	class DeleteContact extends AsyncTask<Void, Void, Void>{

		List<NameValuePair> listPair;

		String result_from_server = "";
		
		long primary_key;
		
		DeleteContact(DatabaseContact contact){
			listPair = contact.toListNameValuePair();
			primary_key = contact.getPrimaryKey();
		}
		
		@Override
		protected Void doInBackground(Void... params) {
			HttpRequest request = new HttpRequest();
			result_from_server = request.makeServiceCall(
					ConstantsFileName.URL_CONTACT_DELETE, HttpRequest.POST,
					listPair);
			return null;
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}

		@Override
		protected void onPostExecute(Void result) {

			super.onPostExecute(result);
			
			if (result_from_server == null || result_from_server.equals(null)
					|| result_from_server.equals("")) {
				mAlertDialog = new ViewAlertDialogManager();
				mAlertDialog.showAlertDialog(context, "Request timeout !",
						"Something for work is incorrect ! Please try again !",
						false);
			}else{
				Log.e(TAG, result_from_server);
				try {
					JSONObject jsonObject = new JSONObject(result_from_server);
					int success = jsonObject
							.getInt(ConstantsFileName.success_field);

					if (success == 1) {
						db.deleteContact(primary_key);
						mAlertDialog = new ViewAlertDialogManager();
						mAlertDialog.showAlertDialog(context, "Success !",
								"Contact has been remove in server!",
								false);
						initListContact();
						selectPage(0);
					}else{
						mAlertDialog = new ViewAlertDialogManager();
						mAlertDialog.showAlertDialog(context, "Delete contact error !",
								"An incident that occurred when deleting contact: "+jsonObject.getString(ConstantsFileName.log_field) ,
								false);
					}
				}catch(Exception e){
					e.printStackTrace();
				}
			}
			
		}
	}
	
	private MobPartnerAdListener mInsterstitialListener = new MobPartnerAdListener() {
		
		@Override
		public void onStartDownloadAds(MobPartnerAdView arg0) {

			Log.e(TAG, "Downloading Interstitial Ads");
		}
		
		@Override
		public void onLoadAdSucceeded(MobPartnerAdView arg0,
				MobPartnerAdCampaign arg1) {

			Log.e(TAG, "Interstitial Load succeeded");
		}
		
		@Override
		public void onLoadAdFailed(MobPartnerAdView arg0, String arg1) {

			Log.e(TAG, "Interstitial load failed, please check if there is any Interstitial in your pool");
		}
		
		@Override
		public void onAdDisappeared(MobPartnerAdView arg0) {

			
		}
		
		@Override
		public void onAdClicked(MobPartnerAdView arg0, MobPartnerAdObject arg1) {

			
		}
		
		@Override
		public void onAdChanged(MobPartnerAdView arg0, MobPartnerAdObject arg1) {

			
		}
	};
	
	/**
	 * Show hide mode layout of setting form
	 * @param mode
	 * 0 - show 3 layout 
	 * 1 - show change password layout
	 * 2 - show change security layout
	 */
	void showHideLinearSettingContent(int mode){
		linearShowChangePassword.setVisibility(View.GONE);
		linearChangePassword.setVisibility(View.GONE);
		linearShowChangeSecurityKey.setVisibility(View.GONE);
		linearChangeSecurityKey.setVisibility(View.GONE);
		linearRateApp.setVisibility(View.GONE);
		linearOtherApp.setVisibility(View.GONE);
		viewShowSetting.setVisibility(View.GONE);
		linearShareApp.setVisibility(View.GONE);
		linearAboutUs.setVisibility(View.GONE);
		linearFakeApp.setVisibility(View.GONE);
		linearSignOut.setVisibility(View.GONE);
		linearParentSettings.setBackgroundColor(Color.parseColor("#faeab9"));
		switch (mode) {
		case 0:
			getActionBar().setDisplayHomeAsUpEnabled(false);
			viewShowSetting.setVisibility(View.VISIBLE);
			linearShowChangePassword.setVisibility(View.VISIBLE);
			linearShowChangeSecurityKey.setVisibility(View.VISIBLE);
			linearRateApp.setVisibility(View.VISIBLE);
			linearOtherApp.setVisibility(View.VISIBLE);
			linearShareApp.setVisibility(View.VISIBLE);
//			linearAboutUs.setVisibility(View.VISIBLE);
			linearSignOut.setVisibility(View.VISIBLE);
			linearFakeApp.setVisibility(View.VISIBLE);
			break;
		case 1:
			getActionBar().setDisplayHomeAsUpEnabled(true);
			linearParentSettings.setBackgroundColor(Color.parseColor("#F67454"));
			linearChangePassword.setVisibility(View.VISIBLE);
			break;
		case 2:
			getActionBar().setDisplayHomeAsUpEnabled(true);
			linearParentSettings.setBackgroundColor(Color.parseColor("#F67454"));
			linearChangeSecurityKey.setVisibility(View.VISIBLE);
			break;

		default:
			break;
		}
	}
	
	
	/**
	 * Rate this app
	 * show app in play store when click
	 */
	void showAppOnPlayStore(){
		Uri uri = Uri.parse("market://details?id=com.dream.messagealarm");
		Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri);
		try {
			startActivity(goToMarket);
		} catch (ActivityNotFoundException e) {
			startActivity(new Intent(
					Intent.ACTION_VIEW,
					Uri.parse("http://play.google.com/store/apps/details?id=com.dream.messagealarm")));
		}
	}
	
	/**
	 * Open company page
	 */
	void openCompanyPageOnPlayStore(){
		Uri uri = Uri.parse("market://apps/collection/Soft+Tech+VN");
		Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri);
		try {
			startActivity(goToMarket);
		} catch (ActivityNotFoundException e) {
			startActivity(new Intent(
					Intent.ACTION_VIEW,
					Uri.parse("https://play.google.com/store/apps/developer?id=Soft+Tech+VN")));
		}
	}
	
	/**
	 * Share this app
	 */
	void shareApp(){
		Intent sharingIntent = new Intent(Intent.ACTION_SEND);
		sharingIntent.setType("text/plain");
		sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT,
				"http://play.google.com/store/apps/details?id=com.dream.messagealarm");
		startActivity(Intent
				.createChooser(sharingIntent, "Share using"));
	}
	
	/**
	 * About US
	 */
	void aboutUs(){
		
	}
	
	/**
	 * Set function for page keypad
	 */
	void setFunctionForPageKeyPad(){
		for (int i = 0; i < listSecurityImageButton.size(); i++) {
			listSecurityImageButton.get(i).setOnClickListener(
					new OnClickListener() {

						@Override
						public void onClick(View v) {
							if(linearNumberKeypadResult.getVisibility() == View.GONE){
								linearNumberKeypadResult.setVisibility(View.VISIBLE);
							}
							phoneNumberKeypadPage += v.getTag().toString();
							tvPhoneNumberFromKeypad.setText(phoneNumberKeypadPage);
							((Vibrator)getSystemService(VIBRATOR_SERVICE)).vibrate(200);
						}
					});
		}
		
		imgDeletePhoneNumberFromKeypad.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				phoneNumberKeypadPage = phoneNumberKeypadPage.substring(0, phoneNumberKeypadPage.length()-1);
				tvPhoneNumberFromKeypad.setText(phoneNumberKeypadPage);
				if(phoneNumberKeypadPage.length() == 0){
					linearNumberKeypadResult.setVisibility(View.GONE);
				}
				((Vibrator)getSystemService(VIBRATOR_SERVICE)).vibrate(200);
			}
		});
		
		ibtnCallKeypad.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if(phoneNumberKeypadPage.length() > 0 ){
					mFlagCalling = FLAG_CALLING;
					ListenerPhoneState.isInAppDelete = true;
					ListenerPhoneState.phone_number = phoneNumberKeypadPage;
					ControlPhoneAction.makeCall(context ,
							phoneNumberKeypadPage);
				}else{
					((Vibrator)getSystemService(VIBRATOR_SERVICE)).vibrate(200);
					Toast.makeText(context, getResources().getString(R.string.enter_phone_num), Toast.LENGTH_SHORT).show();
				}
			}
		});
		
		ibtnSaveContactKeypad.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if(phoneNumberKeypadPage.length() > 0){
					mContact = new DatabaseContact();
					mContact.setPhoneNumber(phoneNumberKeypadPage);
					selectPage(3);
				}else{
					((Vibrator)getSystemService(VIBRATOR_SERVICE)).vibrate(200);
					Toast.makeText(context, getResources().getString(R.string.enter_phone_num), Toast.LENGTH_SHORT).show();
				}
			}
		});
		
	}
	
	/**
	 * Init for keypad Page
	 */
	void initForKeypadPage(){
		phoneNumberKeypadPage = "";
		tvPhoneNumberFromKeypad.setText(phoneNumberKeypadPage);
		linearNumberKeypadResult.setVisibility(View.GONE);
	}

	@Override
	public void onBackPressed() {
		switch (mode) {
		case 0:
			super.onBackPressed();
			break;
		case 1:
			selectPage(0);
			break;
		case 2:
			super.onBackPressed();
			break;
		case 3:
			selectPage(0);
			break;
		case 4:
			if(viewShowSetting.getVisibility()==View.GONE){
				showHideLinearSettingContent(0);
			}
			break;
		case 5:
			super.onBackPressed();
			break;
		case 6:
			initListCallForm(2);
			selectPage(5);
			break;
		case 7:
			break;
		case 8:
			break;
		case 9:
			initListCallForm(1);
			selectPage(8);
			break;
		case 10:
			selectPage(4);
			break;
		case 11:
			selectPage(9);
			break;
		default:
			selectPage(0);
			break;
		}
		
	}
	
	void sendMMS(String phone, String body , String file_path){
		try {
            //Uri uri = Uri.parse("content://media/external/images/media/1");
           

       //     Uri uri = Uri.parse("file://mnt/sdcard/test.jpg");
           

           
           Uri uri = Uri.parse(file_path);
           Intent i = new Intent(Intent.ACTION_SEND);
           i.putExtra("address",phone);
           i.putExtra("sms_body",body );
           i.putExtra(Intent.EXTRA_STREAM,"file:/"+uri);
           i.setType("image/png");
           startActivity(i);
       } catch (Exception e) {
           e.printStackTrace();
       }
	}
	
}
